import datetime
import logging

from django.db.models.signals import post_save, post_init, post_delete
from django.dispatch import receiver

from finance.api.utils import get_account, create_journal, remove_journal
from points.api.utils import PointDB
from sale.models import SaleOrder, SaleReceipt, SaleReceiptDetail

logger = logging.getLogger("django")


# 初始化
@receiver(post_init, sender=SaleOrder)
def receipt_init(instance, **kwargs):
    instance.old_imprest = instance.imprest


@receiver(post_save, sender=SaleOrder)
def handle_sale_order(sender, instance, created, **kwargs):
    """销售出库单"""
    logger.info('handle_sale_order')

    order_data = {
        "account": instance.account,
        "recv_time": instance.order_time,
        "customer": instance.customer,
        "user": instance.saler,
        "receivable": instance.total_amount,
        "amount": instance.imp_amount,
        "discount_amount": 0,
        "actual_amount": instance.imp_amount,
        "oper": instance.oper_user,
        "sale_order_code": instance.code,
        "flag": 1 if instance.flag == 0 else 2,
    }

    if created and instance.imprest:
        inst = SaleReceipt(**order_data)
        inst.save()
        item = SaleReceiptDetail(receipt_order=inst, sale_order=instance, amount=instance.imp_amount, category=0)
        item.save()
    elif not created:
        if instance.old_imprest and instance.imprest:
            SaleReceipt.objects.filter(sale_order_code=instance.code).update(**order_data)
            item = SaleReceiptDetail.objects.filter(sale_order_id=instance.id, receipt_order__sale_order_code=instance.code).first()
            item.amount = instance.imp_amount
            item.save(update_fields=['amount'])
        else:
            if instance.old_imprest:
                SaleReceipt.objects.filter(sale_order_code=instance.code).delete()
            elif instance.imprest:
                inst = SaleReceipt(**order_data)
                inst.save()
                item = SaleReceiptDetail(receipt_order=inst, sale_order=instance, amount=instance.imp_amount, category=0)
                item.save()

    if instance.flag in [0, 1]:
        account = get_account(instance.account_id)
        if instance.imprest:
            data = {
                'order_no': instance.code,
                'customer': instance.customer or None,
                'order_time': datetime.datetime.now(),
                'account': instance.account or None,
                'source': '销售出库直付' if instance.flag == 0 else '销售退货直收',
                'money': instance.imp_amount,
                'balance': account.balance,
                'user': instance.oper_user or None,
                'desc': instance.remark,
                'created': created,
            }
            logger.info(data)
            # 流水账记录
            create_journal(**data)
            # 增加消费积分记录
            consume_data = {
                'code': instance.code,
                'customer': instance.customer or None,
                'category': 2,      # 消费积分
                'point': instance.imp_amount,
                'user': instance.oper_user or None,
            }
            pointdb = PointDB()
            pointdb.create(**consume_data)

        elif instance.old_imprest and not instance.imprest:
            remove_journal(instance.code)
            pointdb = PointDB()
            pointdb.remove(instance.code)


@receiver(post_delete, sender=SaleOrder)
def handle_sale_order_del(sender, instance, **kwargs):
    """删除销售出库订单"""
    if instance.imprest:
        SaleReceipt.objects.filter(sale_order_code=instance.code).delete()
        logger.info("handle_sale_order_del: {}-{}".format(instance.code, instance.imp_amount))
        remove_journal(instance.code)
        pointdb = PointDB()
        pointdb.remove(instance.code)


@receiver(post_save, sender=SaleReceipt)
def handle_sale_journal(sender, instance, created, **kwargs):
    """流水账"""
    logger.info('handle_sale_journal')

    account = get_account(instance.account_id)

    if instance.flag == 0:
        data = {
            'order_no': instance.code,
            'customer': instance.customer or None,
            'order_time': datetime.datetime.now(),
            'account': instance.account or None,
            'source': '销售订单/退货',
            'money': instance.actual_amount,
            'balance': account.balance,
            'user': instance.oper or None,
            'desc': instance.remark,
            'created': created,
        }
        logger.info(data)
        # 流水账记录
        create_journal(**data)
        # 增加积分
        consume_data = {
            'code': instance.code,
            'customer': instance.customer or None,
            'category': 2,  # 消费积分
            'point': instance.actual_amount,
            'user': instance.oper or None,
        }
        pointdb = PointDB()
        pointdb.create(**consume_data)


@receiver(post_delete, sender=SaleReceipt)
def handle_remove_sale_journal(sender, instance, **kwargs):
    """删除支付订单"""
    logger.info("handle_remove_sale_journal: {}-{}".format(instance.code, instance.actual_amount))
    remove_journal(instance.code)
    pointdb = PointDB()
    pointdb.remove(instance.code)
